<?php
$_base_path = '/var/www/torrent_tracker/filelistwatcher';
// Include the init for the application
ini_set( 'include_path', ini_get('include_path') .
        PATH_SEPARATOR . $_base_path
        );
require( 'init.inc.php' );

// Example code
// my_DBG( $_SERVER );

$username = 'hydrarulz';
$password = base64_decode('bWFyZmFudWU=');

$urls['home'] = 'http://filelist.ro/';
$urls['download'] = 'http://filelist.ro/download.php';
$urls['login'] = 'http://filelist.ro/takelogin.php';
$urls['logged'] = 'http://filelist.ro/my.php';
$urls['browse'][] = 'http://filelist.ro/browse.php';
$urls['browse'][] = 'http://filelist.ro/browse.php?page=1';
$urls['browse'][] = 'http://filelist.ro/browse.php?page=2';

// Login

$lurker = curl_init();

curl_setopt( $lurker, CURLOPT_COOKIEFILE, 'cookiefile.txt' );
curl_setopt( $lurker, CURLOPT_COOKIEJAR, 'cookiefile.txt' );

my_DBG( 'Visiting home...' );

$home = get_web_page( $urls['home'], $lurker );

my_DBG( 'Done' );

$options = array(
    CURLOPT_RETURNTRANSFER      => true,     // return web page
    CURLOPT_HEADER              => false,    // don't return headers
    CURLOPT_FOLLOWLOCATION      => true,     // follow redirects
    CURLOPT_ENCODING            => "",       // handle all encodings
    CURLOPT_USERAGENT           => "spider", // who am i
    CURLOPT_AUTOREFERER         => true,     // set referer on redirect
    CURLOPT_CONNECTTIMEOUT      => 120,      // timeout on connect
    CURLOPT_TIMEOUT             => 120,      // timeout on response
    CURLOPT_MAXREDIRS           => 10,       // stop after 10 redirects
    CURLOPT_SSL_VERIFYHOST      => 0,       // stop after 10 redirects
    CURLOPT_COOKIESESSION       => true
);

curl_setopt_array( $lurker, $options );

curl_setopt( $lurker, CURLOPT_POST, true );
curl_setopt( $lurker, CURLOPT_URL, $urls['login'] );
curl_setopt( $lurker, CURLOPT_POSTFIELDS, array(
    'username' => $username,
    'password' => $password
) );



my_DBG( 'Logging in...' );

$logged = curl_exec( $lurker );
$info = curl_get_info( $lurker );

my_DBG( 'Done' );

if ( $info['header']['url'] != $urls['logged'] )
{
    my_DBG( 'Cannot login!' );
    my_DBG( $info );
    exit;
}

curl_setopt( $lurker, CURLOPT_POST, false );

foreach( $urls['browse'] as $u )
{
    curl_setopt( $lurker, CURLOPT_URL, $u );
    $page = curl_exec( $lurker );
    
    preg_match_all( '/<td><a href="download.php(.*?)<img src=pic/', $page, $torrents );
    
    my_DBG( '---', 1 );
    
    foreach( $torrents[1] as $t )
    {
        $torrent_data = explode( $t, $page );
        $torrent_data = explode( '</tr>', $torrent_data[1] );
        $torrent_data = $torrent_data[0];
                
        preg_match_all( '/<td align="right"><b><a href="details.php\?id=([\d]+?)&/', $torrent_data, $uid );
        $uid = (int)$uid[1][0];
        
        if ( $uid <= 0 )
        {
            continue;
        }
        
        my_DBG( 'Processing '. $uid );
        
        if ( preg_match_all( '/<td align=center>(.*?)<br>time<\/td>/', $torrent_data, $download_times ) == 0 )
        {
            if ( preg_match_all( '/<td align=center>(.*?)<br>ori<\/td>/', $torrent_data, $download_times ) == 0 )
            {
                my_DBG( 'Skipping ...' );                
                continue;
            }
        }
        $download_times = str_replace( ',', '', $download_times[1][0] );
        my_DBG( 'Downloads right now '. $download_times );
        
        $torrent_found = $Torrent->find_by( 'uid', $uid );
        if ( count( $torrent_found ) )
        {
            my_DBG( 'Found' );
            $torrent_id = $torrent_found[0][$Torrent->TABLE_COLUMNS['id']];
        }
        else
        {
            my_DBG( 'Not found' );
            preg_match_all( '/\/([\d]+?)\/(.*?).torrent"/' , $t, $torrent_name );
            $torrent_name = $torrent_name[2][0];
            $torrent_added = $Torrent->add( array( 
                'torrent' => urldecode( $torrent_name ),
                'download_link' => $urls['download'] . str_replace( "%2F", "/", urlencode( substr( $t, 0, -2 ) ) ),
                'uid' => $uid
                ) );
            if (  $torrent_added )
            {
                my_DBG( 'Added '. $torrent_added );
            }
            $torrent_id = $torrent_added;
        }
        
        $watchlist_added = $Watchlist->add( array(
                'torrent' => $torrent_id,
                'downloads' => $download_times
            ) );
        
        if ( !$watchlist_added )
        {
            my_DBG( 'Error: Could not add to watch' );
        }
        
        $torrent_history = $Watchlist->find_by( 'torrent', $torrent_id, 3, null, true );
        
        if ( count( $torrent_history ) == 3 )
        {
            $down2 = $torrent_history[0][$Watchlist->TABLE_COLUMNS['downloads']];
            $down1 = $torrent_history[1][$Watchlist->TABLE_COLUMNS['downloads']];
            $down0 = $torrent_history[2][$Watchlist->TABLE_COLUMNS['downloads']];
            
            $time2 = $torrent_history[0][$Watchlist->TABLE_COLUMNS['time']];
            $time1 = $torrent_history[1][$Watchlist->TABLE_COLUMNS['time']];
            $time0 = $torrent_history[2][$Watchlist->TABLE_COLUMNS['time']];
            
            preg_match_all( '/([\d]{4}?)-([\d]{2}?)-([\d]{2}?) ([\d]{2}?):([\d]{2}?):([\d]{2}?)/', $time2, $time2_parts );
            preg_match_all( '/([\d]{4}?)-([\d]{2}?)-([\d]{2}?) ([\d]{2}?):([\d]{2}?):([\d]{2}?)/', $time1, $time1_parts );
            preg_match_all( '/([\d]{4}?)-([\d]{2}?)-([\d]{2}?) ([\d]{2}?):([\d]{2}?):([\d]{2}?)/', $time0, $time0_parts );
            
            $utime2 = mktime( $time2_parts[4][0], $time2_parts[5][0], $time2_parts[6][0], $time2_parts[2][0], $time2_parts[3][0], $time2_parts[1][0] );
            $utime1 = mktime( $time1_parts[4][0], $time1_parts[5][0], $time1_parts[6][0], $time1_parts[2][0], $time1_parts[3][0], $time1_parts[1][0] );
            $utime0 = mktime( $time0_parts[4][0], $time0_parts[5][0], $time0_parts[6][0], $time0_parts[2][0], $time0_parts[3][0], $time0_parts[1][0] );
            
            $d10 = ( $down1 - $down0 ) / ( $utime1 - $utime0 );
            $d21 = ( $down2 - $down1 ) / ( $utime2 - $utime1 );
            
            $coef = $d21 - $d10;
            
            if ( $coef > 0.6 )
            {
                $torrent_aux = $Torrent->find_by( 'id', $torrent_id );
                if ( count( $torrent_aux ) == 1 )
                {
                    if ( $torrent_aux[$Torrent->TABLE_COLUMNS['downloaded']] == 0 )
                    {
                        $torrent_aux = $torrent_aux[0];
                        $torrent_aux_url = $torrent_aux[$Torrent->TABLE_COLUMNS['download_link']];
                        $torrent_aux_name = $torrent_aux[$Torrent->TABLE_COLUMNS['torrent']];
                        
                        $path_to_save = '/root/watch/';
                        $file_to_save = $path_to_save . $torrent_aux_name .'.torrent';

                        my_DBG( 'Downloading "'. $torrent_aux_url .'" to '. $file_to_save );
                        my_DBG( 'Downloading "'. $torrent_aux_url .'" to '. $file_to_save, 1 );
                        
                        $torrent = get_web_page( $torrent_aux_url, $lurker );
                        $file_written = FALSE;
                        $file_written = file_put_contents( $file_to_save, $torrent['content'] );
                        
                        if ( $file_written !== FALSE )
                        {
                            $Torrent->modify_data_for_id( $torrent_id, array( 'downloaded' => 1 ) );
                        }
                    }
                }
            }
            
            $Speed->add( array(
                'torrent' => $torrent_id,
                'speed' => $coef,
                'data' => json_encode( array( $down0, $down1, $down2 ) )
            ) );
            
            my_DBG( $torrent_id .' -> '. ( $coef ), 1 );
            my_DBG( $down0 ."\t". $down1 ."\t". $down2, 1 );
            
        }
        
        //exit;
        my_DBG( '---', 1 );
        my_DBG( '-----------------------------------------------------------------------------------------' );
    }
    
    
//    my_DBG( $torrents, 1 );
    
    //my_DBG( $page );
}

?>